package com.jie.common.util;

import java.io.IOException;
import java.io.OutputStream;

/**
 * 用于处理socket的outputStream的工具类
 * @author XieZhiJie
 * @date 2022/04/21 15:33
 */
public class OutputStreamUtil {

    /**
     * 发送一个报文, 发送的时候会添加一个MessageConstant.MESSAGE_HEAD_LENGTH长的报文头
     * @param outputStream outputStream
     * @param messageBytes 报文字节
     * @throws IOException IOException
     */
    public static void writeMessage(OutputStream outputStream, byte[] messageBytes) throws IOException {
        byte[] messageBytesLengthBytes = BytesUtil.transformIntToBytes(messageBytes.length);
        byte[] sendMessageBytes = new byte[messageBytesLengthBytes.length + messageBytes.length];
        System.arraycopy(messageBytesLengthBytes, 0, sendMessageBytes, 0, messageBytesLengthBytes.length);
        System.arraycopy(messageBytes, 0, sendMessageBytes, messageBytesLengthBytes.length, messageBytes.length);
        outputStream.write(sendMessageBytes);
        outputStream.flush();
    }

}
